package com.hqj.controller;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.hqj.config.JwtUtils;
import com.hqj.controller.dto.LoginDto;
import com.hqj.entity.User;
import com.hqj.service.UserService;
import com.hqj.utils.Result;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 黄啟军
 * @version 1.0
 * @date 2020/5/16/016
 */
@Api(tags = "UserController")
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Resource
    JwtUtils jwtUtils;
   @Resource
    private UserService userService;
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        System.out.println(loginDto.toString());
        User user = userService.findUser(loginDto.getUsername());
        Assert.notNull(user,"用户不存在");
        if(user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.error("用户名或密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization",jwt);
        response.setHeader("Access-control-Expose-Headers","Authorization");
        return Result.success(MapUtil.builder()
                .put("id",user.getId())
                .put("username",user.getUsername())
                .put("avatar",user.getAvatar()).map()
        );
    }
}
